<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\wxapp\controller;

use api\wxapp\controller\ApiBaseController;
use think\Db;
use api\wxapp\model\Cart;
class CartController extends ApiBaseController
{
    public function index(Cart $cart)
    {
        $params = $this->getParam();
        $this->checkuid($params);
        $list = $cart->getList($params);
        $this->success('请求成功!',$list);
    }

    //添加购物车
    public function add()
    {
        $params = $this->getParam();
        $this->checkuid($params);
        $this->checkgoodsId($params);
        $find =  Cart::where(['uid'=>$params['uid'],'goods_id'=>$params['goods_id']])->find();
        if($find){
            $this->error('购物车已存在此商品,不能重复添加!!!!');
        }
        $params['addtime'] = $this->returnDateTime();
        $res = Cart::insert($params);
        if($res){
            $this->success('请求成功!');
        }else{
            $this->error('请求失败!');
        }
    }
    //删除购物车 商品
    public function delete()
    {
        $params = $this->getParam();
        $this->checkid($params);
        $res = Cart::destroy($params['id']);
        if($res){
            $this->success('请求成功!',true);
        }else{
            $this->error('请求失败!',false);
        }
    }

    public function put()
    {
        $params = $this->getParam();
        $this->checkid($params);
        //定义参数   plus 加号 reduce:减  num 为直接数字
        if(!isset($params['type']) && !isset($params['num'])){
            $this->error('参数缺失!!!!!');
        }
        //setInc 加 setDec 减
        if(isset($params['type'])){
            if($params['type'] == 'plus'){
                $res = Cart::where('id',$params['id'])->setInc('goods_num');
            }elseif($params['type'] == 'reduce'){
                $find = Cart::find($params['id']);
                if($find['goods_num'] > 1){
                    $res = Cart::where('id',$params['id'])->setDec('goods_num');
                }else{
                    $this->error('数量为1,不能在减少');
                }
            }else{
                $this->error('参数缺失');
            }
        }
        if(isset($params['num'])){
            $params['num'] == 0 ? $this->error('数量不能为0') : '';
            $res = Cart::update(['id'=>$params['id'],'goods_num'=>$params['num']]);
        }
        if($res){
            $this->success('请求成功!',$res);
        }else{
            $this->error('请求失败');
        }
    }
}
